package com.niodata.dp.task.dao.handler;

import com.niodata.dp.mybatis.DpMybatisTypeHandler;
import com.niodata.dp.task.entity.PackageDefaultParams;
import com.niodata.dp.util.JsonUtil;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class PackageDefaultParamsTypeHandler extends BaseTypeHandler<PackageDefaultParams>
    implements DpMybatisTypeHandler {

  @Override
  public JdbcType getJdbcType() {
    return JdbcType.LONGVARCHAR;
  }

  @Override
  public Class<PackageDefaultParamsTypeHandler> getTypeHandlerClass() {
    return PackageDefaultParamsTypeHandler.class;
  }

  @Override
  public Class<PackageDefaultParams> getJavaClass() {
    return PackageDefaultParams.class;
  }

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, PackageDefaultParams parameter,
      JdbcType jdbcType) throws SQLException {
    try {
      String json = JsonUtil.toJson(parameter);
      ps.setString(i, json);
    } catch (IOException ioe) {
      throw new RuntimeException(ioe);
    }
  }

  @Override
  public PackageDefaultParams getNullableResult(ResultSet rs, String columnName)
      throws SQLException {
    String json = rs.getString(columnName);
    if (json == null) {
      return null;
    }
    PackageDefaultParams params = null;
    try {
      params = JsonUtil.fromJson(PackageDefaultParams.class, json);
    } catch (IOException ioe) {
      throw new RuntimeException(ioe);
    }

    return params;
  }

  @Override
  public PackageDefaultParams getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String json = rs.getString(columnIndex);
    if (json == null) {
      return null;
    }
    PackageDefaultParams params = null;
    try {
      params = JsonUtil.fromJson(PackageDefaultParams.class, json);
    } catch (IOException ioe) {
      throw new RuntimeException(ioe);
    }
    return params;
  }

  @Override
  public PackageDefaultParams getNullableResult(CallableStatement cs, int columnIndex)
      throws SQLException {
    String json = cs.getString(columnIndex);
    if (json == null) {
      return null;
    }
    PackageDefaultParams params = null;
    try {
      params = JsonUtil.fromJson(PackageDefaultParams.class, json);
    } catch (IOException ioe) {
      throw new RuntimeException(ioe);
    }
    return params;
  }
}
